package com.tzpay.tzpay.db;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;

import com.tzpay.tzpay.bean.OrderInfo;
import com.tzpay.tzpay.common.StaticVars;
import com.tzpay.tzpay.utils.T;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by chenfeiyue on 16/4/7.
 */
public class OrderDBUtil {
    private static final java.lang.String TAG = "OrderDBUtil";
    private static OrderDBUtil util;
    private static Context mContext;

    public static synchronized OrderDBUtil getInstance(Context context) {
        mContext = context.getApplicationContext();
        if (util == null) {
            util = new OrderDBUtil();
        }
        return util;
    }

    private OrderDBUtil() {
    }

    public synchronized void initDB() {
        Cursor cursor = mContext.getContentResolver().query(StaticVars.URI.ORDER_INFO,
                null,
                null,
                null,
                null);
        if (cursor != null) {
            StaticVars.ORDERINFO_CURR_COUNT = cursor.getCount();
            cursor.close();
        }
    }

    public synchronized void insert(OrderInfo info) {
        ContentValues values = createContentValues(info);
        if (null == values) {
            return;
        }
        mContext.getContentResolver().insert(StaticVars.URI.ORDER_INFO,
                values);
    }

    private ContentValues createContentValues(OrderInfo info) {
        ContentValues values = new ContentValues();
        String orderNo = info.getOrderNo();

        /**
         * 没有订单号，返回
         */
        if (TextUtils.isEmpty(orderNo)) {
            return null;
        }
        values.put(StaticVars.Column.ORDER_NO, orderNo);
        String orderReqNo = info.getOrderReqNo();
        if (!TextUtils.isEmpty(orderReqNo))
            values.put(StaticVars.Column.ORDER_REQ_NO, orderReqNo);
        String merchantId = info.getMerchantId();
        if (!TextUtils.isEmpty(merchantId))
            values.put(StaticVars.Column.MERCHAT_ID, merchantId);
        String subMerchantId = info.getSubMerchantId();
        if (!TextUtils.isEmpty(subMerchantId))
            values.put(StaticVars.Column.SUB_MERCHAT_ID, subMerchantId);
        String orderDate = info.getOrderDate();
        if (!TextUtils.isEmpty(orderDate))
            values.put(StaticVars.Column.ORDER_DATE, orderDate);
        String orderAmt = info.getOrderAmt();
        if (!TextUtils.isEmpty(orderAmt))
            values.put(StaticVars.Column.ORDER_AMT, orderAmt);
        String productAmt = info.getProductAmt();
        if (!TextUtils.isEmpty(productAmt))
            values.put(StaticVars.Column.PRODUCT_AMT, productAmt);
        String attachAmt = info.getAttachAmt();
        if (!TextUtils.isEmpty(attachAmt))
            values.put(StaticVars.Column.ATTACH_AMT, attachAmt);
        String goodsName = info.getGoodsName();
        if (!TextUtils.isEmpty(goodsName))
            values.put(StaticVars.Column.GOODS_NAME, goodsName);
        String storeId = info.getStoreId();
        if (!TextUtils.isEmpty(storeId))
            values.put(StaticVars.Column.STORE_ID, storeId);
        String ourTransNo = info.getOurTransNo();
        if (!TextUtils.isEmpty(ourTransNo))
            values.put(StaticVars.Column.OUR_TRANS_NO, ourTransNo);
        String errorCode = info.getErrorCode();
        if (!TextUtils.isEmpty(errorCode))
            values.put(StaticVars.Column.ERROR_CODE, errorCode);

        String errorMsg = info.getErrorMsg();
        if (!TextUtils.isEmpty(errorMsg))
            values.put(StaticVars.Column.ERROR_MSG, errorMsg);
        String refundFlag = info.getRefundFlag();
        if (!TextUtils.isEmpty(refundFlag))
            values.put(StaticVars.Column.REFUND_FLAG, refundFlag);
        String customerId = info.getCustomerId();
        if (!TextUtils.isEmpty(customerId))
            values.put(StaticVars.Column.CUSTOMER_ID, customerId);
        String refundReqNo = info.getRefundReqNo();
        if (!TextUtils.isEmpty(refundReqNo))
            values.put(StaticVars.Column.REFUND_REQ_NO, refundReqNo);
        String refundReqDate = info.getRefundReqDate();
        if (!TextUtils.isEmpty(refundReqDate))
            values.put(StaticVars.Column.REFUND_REQ_DATE, refundReqDate);
        String transAmt = info.getTransAmt();
        if (!TextUtils.isEmpty(transAmt))
            values.put(StaticVars.Column.TRANS_AMT, transAmt);
        String transStatus = info.getTransStatus();
        if (!TextUtils.isEmpty(transStatus))
            values.put(StaticVars.Column.TRANS_STATUS, transStatus);
        String encodeType = info.getEncodeType();
        if (!TextUtils.isEmpty(encodeType))
            values.put(StaticVars.Column.ENCODE_TYPE, encodeType);
        String sign = info.getSign();
        if (!TextUtils.isEmpty(sign))
            values.put(StaticVars.Column.SIGN, sign);

        String barcode = info.getBarcode();
        if (!TextUtils.isEmpty(barcode))
            values.put(StaticVars.Column.BARCODE, barcode);
        String channel = info.getChannel();
        if (!TextUtils.isEmpty(channel))
            values.put(StaticVars.Column.CHANNEL, channel);
        String busiType = info.getBusiType();
        if (!TextUtils.isEmpty(busiType))
            values.put(StaticVars.Column.BUSI_TYPE, busiType);
        String backUrl = info.getBackUrl();
        if (!TextUtils.isEmpty(backUrl))
            values.put(StaticVars.Column.BACK_URL, backUrl);
        String ledgerDetail = info.getLedgerDetail();
        if (!TextUtils.isEmpty(ledgerDetail))
            values.put(StaticVars.Column.LEDGER_DETAIL, ledgerDetail);
        String temp1 = info.getTemp1();
        if (!TextUtils.isEmpty(temp1))
            values.put(StaticVars.Column.TEMP_1, temp1);
        String temp2 = info.getTemp2();
        if (!TextUtils.isEmpty(temp2))
            values.put(StaticVars.Column.TEMP_2, temp2);
        String temp3 = info.getTemp3();
        if (!TextUtils.isEmpty(temp3))
            values.put(StaticVars.Column.TEMP_3, temp3);
        String temp4 = info.getTemp4();
        if (!TextUtils.isEmpty(temp4))
            values.put(StaticVars.Column.TEMP_4, temp4);
        String temp5 = info.getTemp5();
        if (!TextUtils.isEmpty(temp5))
            values.put(StaticVars.Column.TEMP_5, temp5);
        String temp6 = info.getTemp6();
        if (!TextUtils.isEmpty(temp6))
            values.put(StaticVars.Column.TEMP_6, temp6);
        String temp7 = info.getTemp1();
        if (!TextUtils.isEmpty(temp7))
            values.put(StaticVars.Column.TEMP_7, temp7);
        String temp8 = info.getTemp8();
        if (!TextUtils.isEmpty(temp8))
            values.put(StaticVars.Column.TEMP_8, temp8);
        String temp9 = info.getTemp9();
        if (!TextUtils.isEmpty(temp9))
            values.put(StaticVars.Column.TEMP_9, temp9);
        String temp10 = info.getTemp10();
        if (!TextUtils.isEmpty(temp10))
            values.put(StaticVars.Column.TEMP_10, temp10);
        String uploadFlag = info.getUploadFlag();
        if (!TextUtils.isEmpty(uploadFlag))
            values.put(StaticVars.Column.UPLOAD_FLAG, uploadFlag);
        return values;
    }

    public synchronized boolean updateOrInsert(OrderInfo info) {
        T.e(TAG, "updateOrInsertOrderInfo ------> " + info);
        String orderNo = info.getOrderNo();
        if (TextUtils.isEmpty(orderNo)) {
            return false;
        }
        Cursor cursor = null;
        ContentResolver contentResolver = mContext.getContentResolver();
        try {
            // null 返回所有列
            String selection = StaticVars.Column.ORDER_NO + " = ?";

            String[] selectionArgs = new String[]{info.getOrderNo()};
            cursor = contentResolver.query(StaticVars.URI.ORDER_INFO, null, selection, selectionArgs, null);
            if (cursor != null && cursor.getCount() > 0) {
                // update
                update(info);
                return true;
            }
            insert(info);
            return true;
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    /**
     * @param uploadFlag
     * @return
     */
    public synchronized List<OrderInfo> getOrderInfos(String uploadFlag) {
        String selection = StaticVars.Column.UPLOAD_FLAG + " = ? ";
        String[] selectionArgs = new String[]{uploadFlag};
        Cursor cursor = mContext.getContentResolver().query(
                StaticVars.URI.ORDER_INFO, null, selection,
                selectionArgs, null);
        if (cursor == null) {
            return null;
        }
        if (cursor.getCount() == 0) {
            cursor.close();
            return null;
        }
        List<OrderInfo> items = new ArrayList<>();
        while (cursor.moveToNext()) {
            OrderInfo item = getOrderInfo(cursor);
            items.add(item);
        }
        cursor.close();
        return items;
    }

    /**
     * 赋值
     *
     * @param cursor
     * @return
     */
    private OrderInfo getOrderInfo(Cursor cursor) {
        OrderInfo item = new OrderInfo();
        item.set_id(cursor.getInt(cursor
                .getColumnIndex(StaticVars.Column._ID)));
        item.setOrderNo(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.ORDER_NO)));
        item.setOrderReqNo(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.ORDER_REQ_NO)));
        item.setMerchantId(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.MERCHAT_ID)));
        item.setSubMerchantId(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.SUB_MERCHAT_ID)));
        item.setOrderDate(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.ORDER_DATE)));
        item.setOrderAmt(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.ORDER_AMT)));
        item.setProductAmt(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.PRODUCT_AMT)));
        item.setAttachAmt(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.ATTACH_AMT)));
        item.setGoodsName(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.GOODS_NAME)));
        item.setStoreId(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.STORE_ID)));
        item.setOurTransNo(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.OUR_TRANS_NO)));
        item.setErrorCode(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.ERROR_CODE)));
        item.setErrorMsg(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.ERROR_MSG)));
        item.setRefundFlag(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.REFUND_FLAG)));
        item.setCustomerId(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.CUSTOMER_ID)));
        item.setRefundReqNo(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.REFUND_REQ_NO)));
        item.setRefundReqDate(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.REFUND_REQ_DATE)));
        item.setTransAmt(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.TRANS_AMT)));
        item.setTransStatus(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.TRANS_STATUS)));
        item.setEncodeType(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.ENCODE_TYPE)));
        item.setSign(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.SIGN)));
        item.setBarcode(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.BARCODE)));
        item.setChannel(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.CHANNEL)));
        item.setBusiType(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.BUSI_TYPE)));
        item.setBackUrl(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.BACK_URL)));
        item.setLedgerDetail(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.LEDGER_DETAIL)));
        item.setTemp1(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.TEMP_1)));
        item.setTemp2(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.TEMP_2)));
        item.setTemp3(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.TEMP_3)));
        item.setTemp4(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.TEMP_4)));
        item.setTemp5(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.TEMP_5)));
        item.setTemp6(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.TEMP_6)));
        item.setTemp7(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.TEMP_7)));
        item.setTemp8(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.TEMP_8)));
        item.setTemp9(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.TEMP_9)));
        item.setTemp10(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.TEMP_10)));
        item.setUploadFlag(cursor.getString(cursor
                .getColumnIndex(StaticVars.Column.UPLOAD_FLAG)));
        return item;
    }

    /**
     * 获取单个对象
     *
     * @param orderNo
     * @return
     */
    public synchronized OrderInfo getOrderInfoByNo(String orderNo) {
        Cursor cursor = mContext.getContentResolver().query(
                StaticVars.URI.ORDER_INFO, null,
                StaticVars.Column.ORDER_NO + " = ? ", new String[]{orderNo},
                null);
        if (cursor == null) {
            return null;
        }
        if (cursor.getCount() == 0) {
            cursor.close();
            return null;
        }
        OrderInfo item = null;
        while (cursor.moveToNext()) {
            item = getOrderInfo(cursor);
        }
        cursor.close();
        return item;
    }

    /**
     * 获取所有对象
     *
     * @return
     */
    public synchronized List<OrderInfo> getOrderInfos() {
        Cursor cursor = mContext.getContentResolver().query(
                StaticVars.URI.ORDER_INFO, null, null, null, null);
        if (cursor == null) {
            return null;
        }
        if (cursor.getCount() == 0) {
            cursor.close();
            return null;
        }
        List<OrderInfo> items = new ArrayList<OrderInfo>();
        while (cursor.moveToNext()) {
            OrderInfo item = getOrderInfo(cursor);
            items.add(item);
        }
        cursor.close();
        return items;
    }


    /**
     * 获取所有对象
     *
     * @return
     */
    public ArrayList<OrderInfo> getOrderInfos(String selection, String[] selectionArgs, String sortOrder) throws Exception {
        Cursor cursor = null;
        try {
            cursor = mContext.getContentResolver().query(
                    StaticVars.URI.ORDER_INFO, null, selection, selectionArgs, sortOrder);
            if (cursor == null) {
                return null;
            }
            if (cursor.getCount() == 0) {
                return null;
            }
            ArrayList<OrderInfo> items = new ArrayList<>();
            while (cursor.moveToNext()) {
                OrderInfo item = getOrderInfo(cursor);

                T.e("OrderDBUtil", item.toString());
                items.add(item);
            }
            return items;
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    /**
     * @return
     */
    public synchronized void deleteAll() {
        mContext.getContentResolver().delete(StaticVars.URI.ORDER_INFO,
                null, null);
    }

    /**
     * @param orderNo
     * @return
     */
    public synchronized void delete(String orderNo) {
        mContext.getContentResolver().delete(StaticVars.URI.ORDER_INFO,
                StaticVars.Column.ORDER_NO + " = ? ", new String[]{orderNo});
    }

    public synchronized void update(OrderInfo info) {
        ContentValues values = createContentValues(info);
        if (values == null) {
            return;
        }
        String where = StaticVars.Column.ORDER_NO + " = ? ";
        String[] selectionArgs = new String[]{info.getOrderNo()};
        mContext.getContentResolver().update(StaticVars.URI.ORDER_INFO, values,
                where, selectionArgs);
    }
}
